package com.csdn.ingo.dao.ctrip.search.dictionary.productscore;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * @Author: ycy
 * @CreateDate: 2019/7/18 10:33
 */
public class CommonUtil {

  private static final String SPACE_REG = "\\s";
  private static final String LEFT_PARENTHESIS = "(";
  private static final String LEFT_PARENTHESIS_CN = "（";
  private static final String HOT_CITY_SPLIT = ",";

  /**
   * 有英文关键词
   */
  public static boolean hasEnglish(String keyword) {
    if (StringUtils.isEmpty(keyword)) {
      return false;
    }

    keyword = keyword.replaceAll("\\s", "").toLowerCase();
    for (char c : keyword.toCharArray()) {
      if (c >= 'a' && c <= 'z') {
        return true;
      }
    }
    return false;
  }


  /**
   * 拼音、英文名特殊字符过滤
   */
  public static String filterPinyinOrEname(String input) {
    if (input == null) {
      return StringUtils.EMPTY;
    }

    String spaceFilterResult = input.replaceAll(SPACE_REG, StringUtils.EMPTY);
    int parentthesisIndex = spaceFilterResult.indexOf(LEFT_PARENTHESIS);
    if (parentthesisIndex != -1) {
      return spaceFilterResult.substring(0, parentthesisIndex);
    }

    parentthesisIndex = spaceFilterResult.indexOf(LEFT_PARENTHESIS_CN);
    if (parentthesisIndex != -1) {
      return spaceFilterResult.substring(0, parentthesisIndex);
    }
    return spaceFilterResult.toLowerCase();
  }

  /**
   * 返回关键词拼音
   */
  public static String getPinyin(String keyword) {
    if (StringUtils.isEmpty(keyword)) {
      return StringUtils.EMPTY;
    }
    StringBuilder pinyins = new StringBuilder();
    for (int i = 0, length = keyword.length(); i < length; i ++) {
      if (keyword.charAt(i) < 'a' || keyword.charAt(i) > 'z') {
        try {
          String[] pys = PinyinMapper.get().get(keyword.charAt(i));
          if (pys != null && pys.length > 0) {
            pinyins.append(pys[0]);
          }
        } catch (IOException e) {
          continue;
        }
      } else {
        pinyins.append(keyword.charAt(i));
      }
    }
    return pinyins.toString();
  }


}
